$(function() {
    load();
}());

function load() {
    if(gcommon.uid()) {
        ghttp.get('/personal/basket/user/' + gcommon.uid(), null, function(resp) {
            if(resp.success) {
                render(resp.result);
            }
        });
    }
}

function render(data) {
    var $blank = $('.blank');
    var $empty = $('.empty');
    if(data.length === 0) {
        $blank.show();
        return;
    }

    // 分组
    var items = []; // { type: "", sid:"", name:"", items: [] }

    for(var i=0; i<data.length; i++) {
        var o = data[i];
        if(o.type == 1) {
            // 菜单品
            items.push({ type: o.type, sid: o.sourceId, name: o.name, items: [ o ] });
        } else {
            // 菜谱
            var exist = getItem(items, o);
            if(exist) {
                exist.items.push(o);
            } else {
                items.push({ type: o.type, sid: o.sourceId, name: o.extra, items: [ o ] });
            }
        }
    }

    // render
    items.forEach(function(item) {
        if(item.type == 1) {
            renderCommodity(item);
        } else {
            renderMenu(item);
        }
    });

    $empty.show();
}

function renderCommodity(item) {
    var $content = $('.content');
    var cls0 = '';
    var cls1 = '';
    if(item.items[0].isChecked == 1) {
        cls0 = 'sel';
        cls1 = 'visiable';
    }

    var id = item.items[0].id;
    var ctype = item.items[0].extra.split(',')[0];
    var cprice = item.items[0].extra.split(',')[1];

    var html = [
        '<div class="material name item-' + id + '" >',
            '<div class="choose ' + cls0 + '" onclick="onClickItem('+ id + ')">',
                '<i class="icon icon-choose ' + cls1 + '">&nbsp;</i>',
            '</div>',
            '<a href="/commodity/' + item.sid + '/type/' + ctype + '?name=' + item.name + '&price=' + cprice + '"><h1 class="title">', item.name , '</h1></a>',
            '<div class="del right" onclick="onDelete(' + item.type + ',' + item.sid + ')">删除</div>',
        '</div>'
    ].join('');
    $content.append(html);
}

function renderMenu(item) {
    var $content = $('.content');
    var html = '<div class="material">';

    html += [
        '<div class="name">',
            '<div class="choose" onclick="onClickAll(' + item.type + ',' + item.sid + ', event)">',
                '<i class="icon icon-choose"></i>',
            '</div>',
            '<h1 class="title"><a href="/menu/' + item.sid + '">', item.name , '</a></h1>',
            '<div class="del right" onclick="onDelete(' + item.type + ',' + item.sid + ')">删除</div>',
        '</div>'
    ].join('');

    html += '<ul class="items">';
    item.items.forEach(function(o) {
        var cls0 = '';
        var cls1 = '';

        if(o.isChecked == "1") {
            cls0 = 'sel';
            cls1 = 'visiable';
        }
        html += [
            '<li class="item item-sid-' + item.sid + ' item-' + o.id + '" onclick="onClickItem('+ o.id + ')" data-v="' + o.id + '">',
                '<div class="title">', o.name ,'</div>',
                '<div class="choose ' + cls0 + '">',
                    '<i class="icon icon-choose ' + cls1 + '"></i>',
                '</div>',
            '</li>'
        ].join('');
    });

    if(item.items.length % 2 !== 0) {
        html += [
            '<li class="item">',
                '<div class="title">&nbsp;</div>',
                '<div class="choose" style="visibility: hidden">',
                '<i class="icon icon-choose"></i>',
                '</div>',
            '</li>'
        ].join('');
    }

    html += '</ul>';
    html += '</div>';
    $content.append(html);
}

function getItem(items, o) {
    var result;
    for(var i=0; i<items.length; i++) {
        if(items[i].type === o.type && items[i].sid === o.sourceId) {
            result = items[i];
            break;
        }
    }
    return result;
}

/****************************** events ******************************/
function onClickItem(id) {
    var $el = $('.item-' + id);
    var $choose = $el.find('.choose');
    var $icon = $el.find('.icon');

    if($choose.hasClass('sel')) {
        $choose.removeClass('sel');
        $icon.removeClass('visiable');
    } else {
        $choose.addClass('sel');
        $icon.addClass('visiable');
    }

    ghttp.post('/personal/basket/' + id + '/isChecked', null, function(resp) {
        // if(resp.success) {
        //
        // }
    });
}

function onClickAll(type, sid, event) {
    var $target = $(event.target);
    if($target.hasClass('icon')) {
        $target = $target.parent();
    }

    var $choose = $target;
    var $icon = $choose.find('.icon');
    var $sid = $('.item-sid-' + sid);

    // for(var i=0; i<$sid.length; i++) {
    //     var id = $(sid[0]).data('v');
    //     var $el = $('.item-' + id);
    // }

    var checked = 0;
    if($choose.hasClass('sel')) {
        $choose.removeClass('sel');
        $icon.removeClass('visiable');

        $sid.find('.choose').removeClass('sel');
        $sid.find('.icon').removeClass('visiable');
    } else {
        checked = 1;
        $choose.addClass('sel');
        $icon.addClass('visiable');

        $sid.find('.choose').addClass('sel');
        $sid.find('.icon').addClass('visiable');
    }

    ghttp.post('/personal/basket/type/' + type + '/sid/' + sid + '/isChecked/' + checked);
}

function onDelete(type, sid) {
    var r = confirm("确定要删除吗?");
    if(r) {
        ghttp.delete('/personal/basket/type/' + type + '/sid/' + sid, null, function(resp) {
            if(resp.success) {

                var count = localStorage.getItem('local-basket-count') || 0;
                if(count > 0) {
                    localStorage.setItem('local-basket-count', count*1-1);
                    if(count*1-1 === 0) {
                        $('.badget').hide();
                    } else {
                        $('.badget').text(count*1-1).show();
                    }
                }

                window.location.reload();
            }
        });
    }
}

function onClear() {
    if(gcommon.uid()) {
        var r = confirm("确定要删除吗?");
        if(r) {
            ghttp.delete('/personal/basket/uid/' + gcommon.uid(), null, function(resp) {
                if(resp.success) {
                    localStorage.removeItem('local-basket-count');
                    window.location.reload();
                }
            });
        }
    }
}